//
//  FDCalendar.m
//  FDCalendarDemo
//
//  Created by fergusding on 15/8/20.
//  Copyright (c) 2015年 fergusding. All rights reserved.
//

#import "FDCalendar.h"
#import "FDCalendarItem.h"
//#import "XLCalenderMarkDays.h"

#define Weekdays @[@"日", @"一", @"二", @"三", @"四", @"五", @"六"]

static NSDateFormatter *dateFormattor;

@interface FDCalendar () <UIScrollViewDelegate, FDCalendarItemDelegate>
{
//    NSMutableArray *monthArr;
    
    IBOutlet UIView *_topView;
    IBOutlet UILabel *_dateLabel;
    IBOutlet UIImageView *_arrowImg;
}

//@property (strong, nonatomic) NSDate *date;

@property (strong, nonatomic) UIButton *titleButton;
@property (strong, nonatomic) UIScrollView *scrollView;
@property (strong, nonatomic) FDCalendarItem *leftCalendarItem;
@property (strong, nonatomic) FDCalendarItem *centerCalendarItem;
@property (strong, nonatomic) FDCalendarItem *rightCalendarItem;
@property (strong, nonatomic) UIView *backgroundView;
@property (strong, nonatomic) UIView *datePickerView;
@property (strong, nonatomic) UIDatePicker *datePicker;

//@property (nonatomic, strong) NSArray *markArr;
//蒙版
@property (nonatomic , strong) UIView *mask;

@end

@implementation FDCalendar

- (instancetype)initWithCurrentDate:(NSDate *)date {
    if (self = [super init]) {
        
        self.date = date;
        self.backgroundColor = [UIColor whiteColor];
        [self setupWeekHeader];
        [self setupCalendarItems];
        [self setupScrollView];
        [self setCurrentDate:self.date];
    }
    return self;
}


#pragma mark - Custom Accessors

- (UIView *)backgroundView {
    if (!_backgroundView) {
        _backgroundView = [[UIView alloc] initWithFrame: self.bounds];
        _backgroundView.backgroundColor = [UIColor blackColor];
        _backgroundView.alpha = 0;
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideDatePickerView)];
        [_backgroundView addGestureRecognizer:tapGesture];
    }
    
    [self addSubview:_backgroundView];
    
    return _backgroundView;
}

- (UIView *)datePickerView {
    if (!_datePickerView) {
        _datePickerView = [[UIView alloc] initWithFrame:CGRectMake(0, 44, self.frame.size.width, 0)];
        _datePickerView.backgroundColor = [UIColor whiteColor];
        _datePickerView.clipsToBounds = YES;
        
        UIButton *cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(20, 10, 35, 20)];
        cancelButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
        [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        [cancelButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [cancelButton addTarget:self action:@selector(cancelSelectCurrentDate) forControlEvents:UIControlEventTouchUpInside];
        [_datePickerView addSubview:cancelButton];
        
        UIButton *okButton = [[UIButton alloc] initWithFrame:CGRectMake(self.frame.size.width - 52, 10, 35, 20)];
        okButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
        [okButton setTitle:@"确定" forState:UIControlStateNormal];
        [okButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [okButton addTarget:self action:@selector(selectCurrentDate) forControlEvents:UIControlEventTouchUpInside];
        [_datePickerView addSubview:okButton];
        
        [_datePickerView addSubview:self.datePicker];
    }
    
    [self addSubview:_datePickerView];
    
    return _datePickerView;
}

- (UIDatePicker *)datePicker {
    if (!_datePicker) {
        _datePicker = [[UIDatePicker alloc] init];
        _datePicker.datePickerMode = UIDatePickerModeDate;
        _datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"Chinese"];
        CGRect frame = _datePicker.frame;
        frame.origin = CGPointMake(0, 32);
        _datePicker.frame = frame;
    }
    
    return _datePicker;
}

#pragma mark - Private

- (NSString *)stringFromDate:(NSDate *)date {
    if (!dateFormattor) {
        dateFormattor = [[NSDateFormatter alloc] init];
        [dateFormattor setDateFormat:@"MM-yyyy"];
    }
    return [dateFormattor stringFromDate:date];
}

// 设置上层的titleBar
- (void)setupTitleBar {
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, 44)];
    titleView.backgroundColor = [UIColor redColor];
    [self addSubview:titleView];
    
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 10, 32, 24)];
    [leftButton setImage:[UIImage imageNamed:@"icon_previous"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(setPreviousMonthDate) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:leftButton];
    
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(titleView.frame.size.width - 37, 10, 32, 24)];
    [rightButton setImage:[UIImage imageNamed:@"icon_next"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(setNextMonthDate) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:rightButton];
    
    UIButton *titleButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    titleButton.titleLabel.textColor = [UIColor whiteColor];
    titleButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    titleButton.center = titleView.center;
    [titleButton addTarget:self action:@selector(showDatePicker) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:titleButton];
    
    self.titleButton = titleButton;
}

// 设置星期文字的显示
- (void)setupWeekHeader {
    NSInteger count = [Weekdays count];
    CGFloat offsetX = 15;
    for (int i = 0; i < count; i++) {
        UILabel *weekdayLabel = [[UILabel alloc] initWithFrame:CGRectMake(offsetX, 15, (DeviceWidth - 30) / count, 16)];
        weekdayLabel.font = [UIFont systemFontOfSize:16];
        weekdayLabel.textAlignment = NSTextAlignmentCenter;
        weekdayLabel.text = Weekdays[i];
        
        weekdayLabel.textColor = colorFromHex(@"#1ebfff");
        [self addSubview:weekdayLabel];
        offsetX += weekdayLabel.frame.size.width;
    }

}

//设置月份显示
-(void)setupTopView{
    _topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DeviceWidth, 44)];
    _topView.backgroundColor = [UIColor whiteColor];
    [self addSubview:_topView];
    
    UIButton *titleButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    titleButton.titleLabel.textColor = [UIColor whiteColor];
    titleButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    titleButton.center = _topView.center;
    [titleButton addTarget:self action:@selector(showDatePicker) forControlEvents:UIControlEventTouchUpInside];
    
    [_topView addSubview:titleButton];
    
}


// 设置包含日历的item的scrollView
- (void)setupScrollView {
    self.scrollView.delegate = self;
    self.scrollView.scrollEnabled = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self.scrollView setFrame:CGRectMake(0, 75-50, DeviceWidth, self.centerCalendarItem.frame.size.height)];
    self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width, self.scrollView.frame.size.height);
    [self addSubview:self.scrollView];
}

// 设置日历
- (void)setupCalendarItems {
    
    self.scrollView = [[UIScrollView alloc] init];
    
    self.centerCalendarItem = [[FDCalendarItem alloc] initWithToday:[NSDate date]];
    self.centerCalendarItem.delegate = self;
    self.centerCalendarItem.markArr = self.markArr;
    self.centerCalendarItem.date = self.centerCalendarItem.today;
    [self.scrollView addSubview:self.centerCalendarItem];
    
    UIView *markView = [[UIView alloc]initWithFrame:CGRectMake(SCREENWIDTH - 135, self.centerCalendarItem.height-29, 120, 29)];
    if ([SYAccountTool ShareAccount].account.lasttype == 1) {
        
        UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 5)];
        view1.centerY = 7;
        [view1 setBackgroundColor:colorFromHex(@"#1ebfff")];
        view1.layer.cornerRadius = 2.5;
        [markView addSubview:view1];
        
        UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(view1.right+5, 0, 45, 14)];
        label1.text = @"全勤";
        label1.font = [UIFont systemFontOfSize:14];
        label1.textColor = colorFromHex(@"#979797");
        [markView addSubview:label1];
        
        UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(label1.right, 0, 5, 5)];
        view2.centerY = 7;
        [view2 setBackgroundColor:colorFromHex(@"#FED516")];
        view2.layer.cornerRadius = 2.5;
        [markView addSubview:view2];
        
        UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(view2.right+5, 0, 45, 14)];
        label2.text = @"未全勤";
        label2.font = [UIFont systemFontOfSize:14];
        label2.textColor = colorFromHex(@"#979797");
        [markView addSubview:label2];
        
    }else {
        UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(-40, 0, 5, 5)];
        view1.centerY = 7;
        [view1 setBackgroundColor:colorFromHex(@"#1ebfff")];
        view1.layer.cornerRadius = 2.5;
        [markView addSubview:view1];
        
        UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(view1.right+5, 0, 60, 14)];
        label1.text = @"考勤正常";
        label1.font = [UIFont systemFontOfSize:14];
        label1.textColor = colorFromHex(@"#979797");
        [markView addSubview:label1];
        
        UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(label1.right+10, 0, 5, 5)];
        view2.centerY = 7;
        [view2 setBackgroundColor:colorFromHex(@"#FED516")];
        view2.layer.cornerRadius = 2.5;
        [markView addSubview:view2];
        
        UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(view2.right+5, 0, 60, 14)];
        label2.text = @"考勤异常";
        label2.font = [UIFont systemFontOfSize:14];
        label2.textColor = colorFromHex(@"#979797");
        [markView addSubview:label2];
    }
    
    [self.scrollView addSubview:markView];
    
}

// 设置当前日期，初始化
- (void)setCurrentDate:(NSDate *)date {
    
    self.centerCalendarItem.markArr = self.markArr;
    self.centerCalendarItem.date = date;

}

#pragma mark - date

- (NSInteger)day:(NSDate *)date{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components day];
}


- (NSInteger)month:(NSDate *)date{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components month];
}

- (NSInteger)year:(NSDate *)date{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components year];
}


- (NSInteger)firstWeekdayInThisMonth:(NSDate *)date{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    [calendar setFirstWeekday:1];//1.Sun. 2.Mon. 3.Thes. 4.Wed. 5.Thur. 6.Fri. 7.Sat.
    NSDateComponents *comp = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    [comp setDay:1];
    NSDate *firstDayOfMonthDate = [calendar dateFromComponents:comp];
    
    NSUInteger firstWeekday = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:firstDayOfMonthDate];
    return firstWeekday - 1;
}

- (NSInteger)totaldaysInThisMonth:(NSDate *)date{
    NSRange totaldaysInMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return totaldaysInMonth.length;
}

- (NSInteger)totaldaysInMonth:(NSDate *)date{
    NSRange daysInLastMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return daysInLastMonth.length;
}

- (NSDate *)lastMonth:(NSDate *)date{
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.month = -1;
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];
    return newDate;
}

- (NSDate*)nextMonth:(NSDate *)date{
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.month = +1;
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];
    return newDate;
}

#pragma mark - 加载数据
// 重新加载日历items的数据
- (void)reloadCalendarItems {
    CGPoint offset = self.scrollView.contentOffset;
    
    if (offset.x > self.scrollView.frame.size.width) {
        [self setNextMonthDate];
    } else if(offset.x < self.scrollView.frame.size.width) {
        [self setPreviousMonthDate];
    }
}

- (void)showDatePickerView {
    [UIView animateWithDuration:0.25 animations:^{
        self.backgroundView.alpha = 0.4;
        self.datePickerView.frame = CGRectMake(0, 44, self.frame.size.width, 250);
    }];
}

- (void)hideDatePickerView {
    [UIView animateWithDuration:0.25 animations:^{
        self.backgroundView.alpha = 0;
        self.datePickerView.frame = CGRectMake(0, 44, self.frame.size.width, 0);
    } completion:^(BOOL finished) {
        [self.backgroundView removeFromSuperview];
        [self.datePickerView removeFromSuperview];
    }];
}

- (void) getmoreMarkDayWithNext:(BOOL)isNext
{
//    monthArr = [[NSMutableArray alloc]initWithObjects:@"2016-01",@"2016-02",@"2016-03",@"2016-04",@"2016-05",@"2016-06", nil];
//    if (isNext) {
//        if ([self year:_today] != [self year:[self nextMonth:self.date]]) {
//            self.date = [self nextMonth:self.date];
//            _dateLabel.text = [NSString stringWithFormat:@"%ld年%ld月",[self year:_date],[self month:_date]];
//            [_arrowImg setX:120];
//        }else {
//            self.date = [self nextMonth:self.date];
//            _dateLabel.text = [NSString stringWithFormat:@"%ld月",[self month:_date]];
//            [_arrowImg setX:56];
//        }
//    }else{
//        if ([self year:_today] != [self year:[self lastMonth:self.date]])
//        {
//            self.date = [self lastMonth:self.date];
//            _dateLabel.text = [NSString stringWithFormat:@"%ld年%ld月",[self year:_date],[self month:_date]];
//            [_arrowImg setX:120];
//        }else
//        {
//            self.date = [self lastMonth:self.date];
//            _dateLabel.text = [NSString stringWithFormat:@"%ld月",[self month:_date]];
//            [_arrowImg setX:56];
//        }
//    }
    
    NSDateFormatter *formatter1 =[[NSDateFormatter alloc]init];
    [formatter1 setDateFormat:@"yyyy-MM"];
    
    //获取上个月的日期
    NSDateComponents *components = [[NSDateComponents alloc] init];
    if (isNext) {
        components.month = +1;
    }else
        components.month = -1;
    
    NSDate *previousMonthDate = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:self.centerCalendarItem.date options:NSCalendarMatchStrictly];
    
    NSString *dateString = [formatter1 stringFromDate:previousMonthDate];
    NSLog(@"%@",dateString);
    
//    if ([[XLCalenderMarkDays sharedManager].markMonths indexOfObject:dateString] == NSNotFound) {
//        NSLog(@"发通知调用接口");
//        
//        NSDateFormatter *formatter =[[NSDateFormatter alloc]init];
//        [formatter setDateFormat:@"yyyy-MM-dd"];
//        NSDateComponents *components = [[NSDateComponents alloc] init];
//        if(isNext){
//            
//        }else
//            components.month = -6;
//        
//        NSDate *previousMonthDate = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:self.centerCalendarItem.date options:NSCalendarMatchStrictly];
//        
//        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
//        [dict setObject:[formatter stringFromDate:previousMonthDate] forKey:@"date"];
//        NSNotification *notification =[NSNotification notificationWithName:@"getMoreMarkDays" object:nil userInfo:dict];
//        //通过通知中心发送通知
//        [[NSNotificationCenter defaultCenter] postNotification:notification];
////        //执行代理
////        [self.delegete getMoreMarkDaysWithDateString:[formatter stringFromDate:previousMonthDate]];
//    }else {
//        NSLog(@"继续");
//    }
}

#pragma mark - SEL

// 跳到上一个月
- (void)setPreviousMonthDate {
    [self setCurrentDate:[self.centerCalendarItem previousMonthDate]];
    NSLog(@"%@",self.centerCalendarItem.date);
    
    [self getmoreMarkDayWithNext:NO];
    
}

// 跳到下一个月
- (void)setNextMonthDate {
    [self setCurrentDate:[self.centerCalendarItem nextMonthDate]];
    
    [self getmoreMarkDayWithNext:YES];
}

- (void)showDatePicker {
    [self showDatePickerView];
}

// 选择当前日期
- (void)selectCurrentDate {
    [self setCurrentDate:self.datePicker.date];
    [self hideDatePickerView];
}

- (void)cancelSelectCurrentDate {
    [self hideDatePickerView];
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self reloadCalendarItems];
    self.scrollView.contentOffset = CGPointMake(self.scrollView.frame.size.width, 0);
}

- (void)setDate:(NSDate *)date {
    _date = date;
    [self setCurrentDate:_date];
}

#pragma mark - FDCalendarItemDelegate

- (void)calendarItem:(FDCalendarItem *)item didSelectedDate:(NSDate *)date {
    
    self.date = date;
    
    NSDate *selectedDate;
    NSTimeInterval  interval =24*60*60*1;
    selectedDate = [NSDate dateWithTimeInterval:interval sinceDate:date];
    [self.delegete didSelectedDate:selectedDate];

}

+ (instancetype)showOnView:(UIView *)view
{
    FDCalendar *calendarPicker = [[FDCalendar alloc]init];
    
    
    float width = [UIApplication sharedApplication].keyWindow.bounds.size.width;
    float height = [UIApplication sharedApplication].keyWindow.bounds.size.height;
    calendarPicker.mask = [[UIView alloc] initWithFrame:CGRectMake(0, 64, width, height)];
    
    calendarPicker.mask.backgroundColor = [UIColor blackColor];
    calendarPicker.mask.alpha = 0.3;
    [[UIApplication sharedApplication].keyWindow addSubview:calendarPicker.mask];
    [[UIApplication sharedApplication].keyWindow addSubview:calendarPicker];
    calendarPicker.backgroundColor = [UIColor whiteColor];
    
    
    return calendarPicker;
}


- (void)show
{
    self.transform = CGAffineTransformTranslate(self.transform, 0, - self.frame.size.height-64);
    [UIView animateWithDuration:0.3 animations:^(void) {
        //        [self customInterface];
        self.transform = CGAffineTransformIdentity;
    } completion:^(BOOL isFinished) {
        //[self customInterface];
    }];
    
//    //首尾式动画
//     [UIView beginAnimations:nil context:nil];
//     //执行动画
//     //设置动画执行时间
//     [UIView setAnimationDuration:2.0];
//     //设置代理
//     [UIView setAnimationDelegate:self];
//     //设置动画执行完毕调用的事件
//     [UIView setAnimationDidStopSelector:@selector(didStopAnimation)];
//     self.center=CGPointMake(200, 300);
//     [UIView commitAnimations];
}

- (void)hide
{
    [UIView animateWithDuration:0.3 animations:^(void) {
        self.transform = CGAffineTransformTranslate(self.transform, 0, - self.frame.size.height);
        self.mask.alpha = 0;
    } completion:^(BOOL isFinished) {
        [self.mask removeFromSuperview];
        [self removeFromSuperview];
    }];
}


- (void)addTap
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hide)];
    [self.mask addGestureRecognizer:tap];
    
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hide)];
    [_topView addGestureRecognizer:tap1];
}
@end
